package com.smfx.yxt.controller.teacher;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.smfx.yxt.common.AppUser;
import com.smfx.yxt.common.Const;
import com.smfx.yxt.common.Constants;
import com.smfx.yxt.common.MenuConst;
import com.smfx.yxt.common.RspResult;
import com.smfx.yxt.common.enums.Status;
import com.smfx.yxt.common.enums.UserRole;
import com.smfx.yxt.controller.BaseController;
import com.smfx.yxt.exception.ExpirationException;
import com.smfx.yxt.model.Grid;
import com.smfx.yxt.model.KccsCourseInfo;
import com.smfx.yxt.model.SysResource;
import com.smfx.yxt.model.TeacherInfo;
import com.smfx.yxt.page.OrderBy;
import com.smfx.yxt.page.Page;
import com.smfx.yxt.reqVo.BasePageQueryVO;
import com.smfx.yxt.reqVo.BaseQueryVO;
import com.smfx.yxt.reqVo.KccsCourseQueryVO;
import com.smfx.yxt.reqVo.KccsCourseReqVO;
import com.smfx.yxt.reqVo.KccsStudentSignReqVO;
import com.smfx.yxt.service.IKccsCourseInfoService;
import com.smfx.yxt.service.ISysResourceService;
import com.smfx.yxt.service.ITeacherService;
import com.smfx.yxt.utils.BeanUtils;
import com.smfx.yxt.utils.MD5Util;
import com.smfx.yxt.utils.StringUtil;
import com.smfx.yxt.utils.WeekComparator;
import com.smfx.yxt.view.KccsCourseSignCountView;
import com.smfx.yxt.view.KccsCourseStudentSignView;
import com.smfx.yxt.view.KccsCourseView;
import com.smfx.yxt.view.SysResourceView;
import com.smfx.yxt.view.TeacherInfoView;

@RequestMapping(Const.TEACHER_ROLE + MenuConst.INTEREST_COURSE)
@Controller
public class KccsCourseController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(KccsCourseController.class);
	
	@Autowired
	private ITeacherService teacherService;
	@Autowired
	private IKccsCourseInfoService kccsCourseInfoService;
	@Autowired
	private ISysResourceService sysResourceService;
	
	@RequestMapping(value={"","/"})
	public String index(Model model) {
		AppUser appUser = getAppUser();
		if(StringUtil.isExistPosition(appUser.getTeacher().getPosition(), "5,3001,3002,3003,3004,3005")) {
			model.addAttribute("isAdmin", true);
		}
		model.addAttribute("isClassTeacher", teacherService.
				isClassTeacher(appUser.getTeacher().getId()));
		return "kccsCourse/index";
	}
	
	@RequestMapping("list")
	public String list(Model model) {
		return "kccsCourse/list";
	}
	
	@RequestMapping("approval/list")
	public String approvalList(Model model) {
		return "kccsCourse/approvalList";
	}
	
	@RequestMapping("detail/{courseId}")
	public String detail(Model model, @PathVariable Integer courseId) {
		model.addAttribute("detail", kccsCourseInfoService.selectViewById(courseId));
		return "kccsCourse/detail";
	}
	
	@RequestMapping("detail/query")
	@ResponseBody Object detailQuery(Integer courseId) {
		BaseQueryVO vo = new BaseQueryVO();
		vo.setId(courseId);
		vo.setTermId(getCurrentTerm().getId());
		return kccsCourseInfoService.selectViewById(courseId);
	}
	
	@RequestMapping("signCourseDetail/{courseId}")
	public String detailQuery(Model model, @PathVariable Integer courseId) {
		BaseQueryVO vo = new BaseQueryVO();
		vo.setId(courseId);
		vo.setTermId(getCurrentTerm().getId());
		model.addAttribute("detail", kccsCourseInfoService.selectSignCourseDetail(vo));
		return "kccsCourse/signCourseDetail";
	}
	
	@RequestMapping("detail/edit/{courseId}")
	public String editDetail(Model model, @PathVariable Integer courseId){
		model.addAttribute("courseId", courseId);
		return "kccsCourse/edit";
	}
	
	@RequestMapping("approvalDetail/{courseId}")
	public String approvalDetail(Model model, @PathVariable Integer courseId){
		model.addAttribute("courseId", courseId);
		if(StringUtil.isExistPosition(getAppUser().getTeacher().getPosition(), "5,3001,3002,3003,3004,3005")) {
			model.addAttribute("isAdmin", true);
		}
		return "kccsCourse/approvalDetail";
	}
	
	@RequestMapping("addCourse")
	public String addCourse(Model model) {
		model.addAttribute("courseId", null);
		return "kccsCourse/edit";
	}
	/**
	 * 我的班级
	 * @param vo
	 * @return
	 */
	@RequestMapping("myClass")
	public String myClass() {
		return "kccsCourse/myClass";
	}
	
	@RequestMapping("myClassFromExt")
	public String myClassFromExt() {
		String teacherId = request.getParameter("tid");
		AppUser appUser = getAppUser();
		if(appUser == null) {
			appUser = new AppUser();
			appUser.setRoleType(UserRole.TEACHER.getCode());
			appUser.setCurrUrl(Const.TEACHER_ROLE);
			TeacherInfo teacher = teacherService.selectById(Integer.valueOf(teacherId));
			TeacherInfoView teacherView = BeanUtils.copyAs(teacher, TeacherInfoView.class);
			appUser.setTeacher(teacherView);
			appUser.setStudyType(teacherView.getStudyType());
			List<SysResource> list = sysResourceService.selectPageByIds(teacher.getPosition());
			List<SysResourceView> viewList = BeanUtils.copyAs(list, SysResourceView.class);
			appUser.setResourceList(viewList);
			request.getSession().setAttribute(Constants.APP_USER, appUser);
		}
		return "kccsCourse/myClass";
	}
	
	/**
	 * 老师任教课程
	 * @return
	 */
	@RequestMapping("teachingCourse")
	public String teachingCourse(Model model) {
		List<KccsCourseInfo> list = kccsCourseInfoService.
				selectListForTeaching(
						getAppUser().getTeacher().getId());
		model.addAttribute("list", list);
		return "kccsCourse/teachingCourse";
	}
	/**
	 * 我创建课程
	 * @param model
	 * @return
	 */
	@RequestMapping("apply/list")
	public String applyList(Model model) {
		List<KccsCourseInfo> list = kccsCourseInfoService.selectApplyList(getAppUser().getTeacher().getId());
		model.addAttribute("list", list);
		return "kccsCourse/applyList";
	}
	
	@RequestMapping("classDate")
	@ResponseBody Object classDate() {
		return kccsCourseInfoService.selectCourseClassDate();
	}

	@RequestMapping("signed/list")
	@ResponseBody Object signedList(KccsCourseQueryVO vo) {
		AppUser appUser = getAppUser();
		vo.setSchoolId(appUser.getTeacher().getSchoolId());
		vo.setTermId(getCurrentTerm().getId());
		vo.setTeacherId(appUser.getTeacher().getId());
		return kccsCourseInfoService.selectSignedListForClass(vo);
	}
	
	@RequestMapping("noSign/list")
	@ResponseBody Object noSignedList(KccsCourseQueryVO vo) {
		AppUser appUser = getAppUser();
		vo.setSchoolId(appUser.getTeacher().getSchoolId());
		vo.setTermId(getCurrentTerm().getId());
		vo.setGrade(appUser.getTeacher().getGrade());
		vo.setTeacherId(appUser.getTeacher().getId());
		return kccsCourseInfoService.selectNoSignListForClass(vo);
	}
	
	@RequestMapping("pending/list")
	@ResponseBody Object pendingList(BasePageQueryVO vo) {
		try {
			Page<KccsCourseInfo> page = new Page<>();
			List<OrderBy> sorts = new ArrayList<>();
			sorts.add(new OrderBy("ID", "asc"));
			page.setSorts(sorts);
			Grid grid = new Grid();
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(Integer.MAX_VALUE - 1);
			List<KccsCourseInfo> list = kccsCourseInfoService.selectPendingList(page);
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return new RspResult(Status.SUCCESS, grid);
		} catch (Exception e) {
			logger.error("--pendingList error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("approved/list")
	@ResponseBody Object approvedList(BasePageQueryVO vo) {
		try {
			Page<KccsCourseInfo> page = new Page<>();
			List<OrderBy> sorts = new ArrayList<>();
			sorts.add(new OrderBy("UPDATE_TIME", "desc"));
			page.setSorts(sorts);
			Grid grid = new Grid();
			page.setParams(vo);
			page.setPageNo(vo.getPage());
			page.setPageSize(Integer.MAX_VALUE - 1);
			List<KccsCourseInfo> list = kccsCourseInfoService.selectApprovedList(page);
			grid.setRows(list);
			grid.setTotal(page.getTotalRecord());
			return new RspResult(Status.SUCCESS, grid);
		} catch (Exception e) {
			logger.error("--approvedList error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("signCourseList")
	@ResponseBody Object signCourseList(BaseQueryVO vo) {
		vo.setStudyType(getAppUser().getTeacher().getStudyType());
		vo.setTermId(getCurrentTerm().getId());
		List<KccsCourseView> list = kccsCourseInfoService.selectSignCourseList(vo);
		return list;
	}
	
	@RequestMapping("signCourseMap")
	@ResponseBody Object signCourseMap(BaseQueryVO vo) {
		vo.setStudyType(getAppUser().getTeacher().getStudyType());
		vo.setTermId(getCurrentTerm().getId());
		List<KccsCourseView> list = kccsCourseInfoService.selectSignCourseList(vo);
		TreeMap<String, List<KccsCourseSignCountView>> map = new TreeMap<>(new WeekComparator());
		for(KccsCourseView view : list) {
			for(KccsCourseSignCountView signView : view.getSignCountList()) {
				if(!map.containsKey(signView.getSignClassDate())) {
					List<KccsCourseSignCountView> signList = new ArrayList<>();
					signList.add(signView);
					map.put(signView.getSignClassDate(), signList);
					continue;
				}
				map.get(signView.getSignClassDate()).add(signView);
			}
		}
		return new RspResult(Status.SUCCESS, map);
	}
	
	@RequestMapping("addUpdate")
	@ResponseBody Object addUpdate(KccsCourseReqVO vo) {
		try {
			vo.setCreaterId(getAppUser().getTeacher().getId());
			vo.setStudyType(getAppUser().getTeacher().getStudyType());
			kccsCourseInfoService.addAndUpdate(vo);
			return new RspResult(Status.SUCCESS);
		} catch (Exception e) {
			logger.error("---addUpdate error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("signSubmit")
	@ResponseBody Object signSubmit(@RequestBody KccsStudentSignReqVO reqVO) {
		try {
			reqVO.setTermId(getCurrentTerm().getId());
			return kccsCourseInfoService.insertSign(reqVO);
		} catch (Exception e) {
			logger.error("---signSubmit error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("changeSubmit")
	@ResponseBody Object changeSubmit(@RequestBody KccsStudentSignReqVO reqVO) {
		try {
			reqVO.setTermId(getCurrentTerm().getId());
			return kccsCourseInfoService.updateChangeSign(reqVO);
		} catch (Exception e) {
			logger.error("---signSubmit error={}", e);
			if(e instanceof ExpirationException) {
				return new RspResult(Status.EXPIRED_DATA.getCode(), e.getMessage());
			}
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("courseApproval")
	@ResponseBody Object courseApproval(KccsCourseReqVO vo) {
		try {
			vo.setApprover(getAppUser().getTeacher().getName());
			vo.setUpdaterId(getAppUser().getTeacher().getId());
			return kccsCourseInfoService.updateApprovalCourse(vo);
		} catch (Exception e) {
			logger.error("---courseApproval error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	@RequestMapping("teachingCourse/stuList")
	@ResponseBody Object teachingCourseStuList(KccsCourseQueryVO vo) {
		try {
			AppUser appUser = getAppUser();
			vo.setTeacherId(appUser.getTeacher().getId());
			vo.setTermId(getCurrentTerm().getId());
			List<KccsCourseStudentSignView> list = kccsCourseInfoService.selectSignListForTeachingByCourseId(vo);
			TreeMap<String, List<KccsCourseStudentSignView>> map = new TreeMap<>(new WeekComparator());
			for(KccsCourseStudentSignView view : list) {
				if(!map.containsKey(view.getSignClassDate())) {
					List<KccsCourseStudentSignView> signList = new ArrayList<>();
					signList.add(view);
					map.put(view.getSignClassDate(), signList);
					continue;
				}
				map.get(view.getSignClassDate()).add(view);
			}
			return new RspResult(Status.SUCCESS, map);
		} catch (Exception e) {
			logger.error("--teachingCourseList error={}", e);
		}
		return new RspResult(Status.FAIL);
	}
	
	
	
	public static void main(String[] args) {
		System.out.println(MD5Util.md5(MD5Util.md5("1")));
	}
}
